<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, h } from "vue";
import { router } from "@/router";
import {
  get_department_ip,
  add_department_ip,
  delete_department_ip,
  update_department_ip,
} from "@/api/asset";
import {
  getFingerprintData,
  deleteFingerprintData,
  addFingerprintData,
  updateFingerprintData,
} from "@/api/task";
import { message } from "@/utils/message";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { DynamicTableInstance } from "@/components/DynamicTable/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import { ElMessage, ElMessageBox } from "element-plus";
import { ActionButtons } from "@/components/DynamicTable/components";

const props = defineProps<{
  task: string;
}>();

defineOptions({
  name: "Weight",
});

// 表单引用
const searchFormRef = ref<DynamicFormInstance>();
const formRef = ref<DynamicFormInstance>();
const tableRef = ref<DynamicTableInstance>();

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const showDialog = ref(false);
const isEdit = ref(false);
const currentId = ref("");

// 开关状态数据
const switchStates = ref({
  adjacentAlgorithm: true, // 相邻算法开关，默认开启
  fingerprintInference: true, // 指纹推理开关，默认开启
});

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 15, 20, 50],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

// 搜索表单数据
const searchFormData = reactive({
  search: "",
});

// 表单数据
const formData = reactive({
  name: "",
  rule: "",
  category: "",
  parent_category: "",
  state: true,
});

// 搜索表单配置
const searchFormConfig: FormItemConfig[] = [
  {
    type: "input",
    key: "search",
    name: "名称",
    placeholder: "名称",
    params: {
      clearable: true,
    },
  },
];

// 表单配置
const formConfig: FormItemConfig[] = [
  {
    type: "input",
    key: "name",
    name: "名称",
    placeholder: "请输入名称",
    required: true,
    rules: [{ required: true, message: "请输入名称", trigger: "blur" }],
  },
  {
    type: "textarea",
    key: "rule",
    name: "规则",
    placeholder: "请输入规则",
    required: true,
    rules: [{ required: true, message: "请输入规则", trigger: "blur" }],
  },
  {
    type: "input",
    key: "category",
    name: "类型",
    placeholder: "请输入类型",
  },
  {
    type: "input",
    key: "parent_category",
    name: "归类",
    placeholder: "请输入归类",
  },
  {
    type: "switch",
    key: "state",
    name: "状态",
    params: {
      activeText: "开",
      inactiveText: "关",
    },
  },
];

// 表格列配置
const tableColumns: TableColumn[] = [
  {
    label: "名称",
    prop: "name",
    show: true,
    key: "name",
  },
  {
    label: "规则",
    prop: "rule",
    show: true,
    key: "rule",
    slot: "rule",
  },
  {
    label: "类型",
    prop: "category",
    show: true,
    key: "category",
  },
  {
    label: "归类",
    prop: "parent_category",
    show: true,
    key: "parent_category",
  },
  {
    label: "资产数量",
    prop: "amount",
    show: true,
    key: "amount",
  },
  {
    label: "状态",
    prop: "state",
    show: true,
    key: "state",
    slot: "state",
  },
  {
    label: "操作",
    prop: "action",
    show: true,
    key: "action",
    fixed: "right",
    slot: "action",
  },
];

// 原始数据
const originalData = ref([]);

// 获取指纹数据列表
const getFingerprintList = async () => {
  loading.value = true;

  try {
    const res = await getFingerprintData({
      search: searchFormData.search,
      pageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
    });

    if (res && res.code === 200) {
      // 根据真实API返回的数据结构处理
      const data = res.data || {};
      originalData.value = data.list || [];
      tableData.value = data.list || [];
      pagination.total = data.total || 0;
    } else {
      // 如果接口返回错误，显示空数据
      originalData.value = [];
      tableData.value = [];
      pagination.total = 0;
      ElMessage.error("获取指纹数据失败");
    }
  } catch (error) {
    console.error("获取指纹数据失败:", error);
    // 接口调用失败，显示空数据
    originalData.value = [];
    tableData.value = [];
    pagination.total = 0;
    ElMessage.error("网络错误，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = (value: any) => {
  // 更新搜索表单数据
  if (value && value.search !== undefined) {
    searchFormData.search = value.search;
  }
  pagination.currentPage = 1;
  getFingerprintList();
};

// 重置搜索
const handleSearchReset = () => {
  searchFormData.search = "";
  searchFormRef.value?.resetFields();
  getFingerprintList();
};

// 提交表单
const handleSubmit = async (value: any) => {
  try {
    let res;
    if (isEdit.value) {
      // 编辑
      res = await updateFingerprintData({
        id: currentId.value,
        name: value.name,
        rule: value.rule,
        category: value.category,
        parent_category: value.parent_category,
        state: value.state,
      });
    } else {
      // 新增
      res = await addFingerprintData({
        name: value.name,
        rule: value.rule,
        category: value.category,
        parent_category: value.parent_category,
        state: value.state,
      });
    }

    if (res && res.code === 200) {
      ElMessage.success(isEdit.value ? "编辑成功" : "添加成功");
      showDialog.value = false;
      getFingerprintList();
    } else {
      ElMessage.error(`${isEdit.value ? "编辑" : "添加"}失败，请稍后重试`);
    }
  } catch (error) {
    console.error(`${isEdit.value ? "编辑" : "添加"}失败:`, error);
    ElMessage.error(`${isEdit.value ? "编辑" : "添加"}失败，请稍后重试`);
  }
};

// 分页处理
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  getFingerprintList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  getFingerprintList();
};

// 取消对话框
const handleCancel = () => {
  showDialog.value = false;
  formRef.value?.resetFields();
};

// 打开新增对话框
const handleOpenAddDialog = () => {
  isEdit.value = false;
  currentId.value = "";
  formData.name = "";
  formData.rule = "";
  formData.category = "";
  formData.parent_category = "";
  formData.state = true;
  showDialog.value = true;
};

// 编辑指纹
const handleEdit = (row: any) => {
  isEdit.value = true;
  currentId.value = row.id;
  formData.name = row.name;
  formData.rule = row.rule;
  formData.category = row.category;
  formData.parent_category = row.parent_category;
  formData.state = row.state;
  showDialog.value = true;
};

// 删除指纹
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除指纹"${row.name}"吗？`, "删除确认", {
      confirmButtonText: "确定删除",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "el-button--danger",
    });

    // 调用删除API
    const res = await deleteFingerprintData({
      ids: [row.id],
    });

    if (res && res.code === 200) {
      ElMessage.success(`指纹"${row.name}"删除成功！`);
      // 重新获取数据
      getFingerprintList();
    } else {
      ElMessage.error("删除失败，请稍后重试");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败，请稍后重试");
    }
  }
};

// 处理开关状态变化
const handleSwitchChange = (
  switchType: string,
  value: string | number | boolean
) => {
  const switchNames: Record<string, string> = {
    adjacentAlgorithm: "相邻算法",
    fingerprintInference: "指纹推理",
  };

  const boolValue = Boolean(value);
  const action = boolValue ? "开启" : "关闭";
  ElMessage.success(`${switchNames[switchType]}已${action}`);

  console.log(`${switchNames[switchType]}状态变化:`, boolValue);
};

// 生命周期
onMounted(() => {
  getFingerprintList();
});

onUnmounted(() => {
  // 清理定时器或其他资源
  loading.value = false;
});
</script>

<template>
  <div>
    <!-- 搜索表单 -->
    <el-card shadow="never">
      <div class="search-form-container">
        <DynamicForm
          ref="searchFormRef"
          v-model="searchFormData"
          :form-config="searchFormConfig"
          :gutter="16"
          label-width="80px"
          type="search"
          @search="handleSearch"
          @reset="handleSearchReset"
        />
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="mt-4">
      <DynamicTable
        ref="tableRef"
        :data="tableData"
        :columns="tableColumns"
        :loading="loading"
        :pagination="pagination"
        :showToolbar="true"
        border
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <template #toolbar-left>
          <el-button type="primary" @click="handleOpenAddDialog">
            新增
          </el-button>
        </template>
        <!-- 规则列插槽 -->
        <template #rule="{ row }">
          <div class="rule-content">
            {{ row.rule }}
          </div>
        </template>

        <!-- 状态列插槽 -->
        <template #state="{ row }">
          <el-tag :type="row.state ? 'success' : 'danger'" effect="dark">
            {{ row.state ? "开启" : "关闭" }}
          </el-tag>
        </template>

        <!-- 操作列插槽 -->
        <template #action="{ row }">
          <el-button size="small" type="primary" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="showDialog"
      :title="isEdit ? '编辑指纹' : '新增指纹'"
      width="600px"
      destroy-on-close
      @close="handleCancel"
    >
      <DynamicForm
        ref="formRef"
        v-model="formData"
        :form-config="formConfig"
        label-width="100px"
        type="submit"
        @submit="handleSubmit"
        @cancel="handleCancel"
      />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-card__header) {
}

:deep(.el-pagination) {
  justify-content: right;
  margin-top: 10px;
  margin-right: 30px;
}
.gather-container {
  display: block;
  margin-bottom: 10px;
}

.min-w-input {
  width: 300px;
}

.el-btn-zese {
  background: #722ed1;
  color: white;
  border-color: #722ed1;
}

.el-btn-zese.is-disabled,
.el-btn-zese.is-disabled:focus,
.el-btn-zese.is-disabled:hover {
  background: #722ed1;
  color: white;
  border-color: #722ed1;
}

// 方法开关样式
.method-switches {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 8px 0;
}

.switch-item {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 120px;
}

.switch-label {
  font-size: 12px;
  color: #606266;
}

.rule-content {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-family: monospace;
  font-size: 12px;
}
</style>
